package com.eclink.iot.rfidclient.controller;

import com.eclink.iot.rfidclient.domain.dto.AjaxResult;
import com.eclink.iot.rfidclient.domain.dto.ResultDTO;
import com.eclink.iot.rfidclient.domain.dto.SerialPortDTO;
import com.eclink.iot.rfidclient.domain.dto.req.OpenSerialReq;
import com.eclink.iot.rfidclient.manager.RFIDManager;
import com.fazecast.jSerialComm.SerialPort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/rfid")
@RestController
public class RfidController {

    private SerialPortDTO buildSerialPortDTO(SerialPort port) {
        SerialPortDTO s = new SerialPortDTO();
        s.setBaudRate(port.getBaudRate());
        s.setOpen(port.isOpen());
        s.setFriendlyName(port.getDescriptivePortName());
        s.setSerialNumber(port.getSerialNumber());
        s.setPortName(port.getSystemPortName());
        s.setVendorID(port.getVendorID());
        return s;
    }

    @GetMapping("/currentSerialPort")
    public AjaxResult getCurrentPort(){
        if (RFIDManager.getCurrentPort()==null) {
            return AjaxResult.fail("RFID端口不存在");
        }
        SerialPort port = RFIDManager.getCurrentPort();
        SerialPortDTO dto = buildSerialPortDTO(port);
        return AjaxResult.success(dto);
    }

    /**
     * 获取串口列表
     * @return 结果
     */
    @GetMapping("/serialports")
    public List<SerialPortDTO> serialports() {
        List<SerialPortDTO> res = new ArrayList<>();
        for(SerialPort port : SerialPort.getCommPorts()) {
            SerialPortDTO dto = buildSerialPortDTO(port);
            res.add(dto);
        }
        return res;
    }


    /**
     * 读
     * @return ResultDTO
     */
    @PostMapping("/read")
    public ResultDTO read() {
        // TODO add your handling code here:

        int areaIndex = 1;//获取操作的区域

        //获取访问密码
        int accessPwdInt = 0;
        System.out.println("访问密码=" + accessPwdInt);

        //获取起始地址
        int addressOffset = 0;

        //获取操作数据的长度
        short operateLength = 2;

        RFIDManager.MsgRead((byte) 0, (byte) areaIndex, (byte) addressOffset, operateLength, accessPwdInt);

        return ResultDTO.success() ;
    }

    @GetMapping("/getReadContent")
    public ResultDTO getReadContent() {
        return ResultDTO.success(RFIDManager.operList.epc);
    }

}
